# -*- codeing = utf-8 -*-
# @Time: 2022/6/18 17:05
# @Author: Foxhuty
# @File: mail_send.py
# @Software: PyCharm
# @Based on python 3.10

import smtplib
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication


def get_server():
    mail_host = 'smtp.qq.com'
    port = 465
    mail_user = '80708055@qq.com'
    passwd = 'jaycecjsmswlcace'
    server = smtplib.SMTP_SSL(host=mail_host, port=port)
    server.login(user=mail_user, password=passwd)
    return server


def send_email(mail_msg, mail_title):
    server = get_server()
    sender = '80708055@qq.com'
    receivers = ['foxhuty@189.cn']
    message = MIMEText(mail_msg, 'plain', 'utf8')
    message['From'] = f'{sender}'
    message['To'] = ','.join(receivers)
    message['Subject'] = mail_title
    server.sendmail(sender, receivers, message.as_string())
    server.quit()


def send_email_with_image(mail_msg, mail_image, mail_title):
    server = get_server()
    sender = '80708055@qq.com'
    receivers = ['foxhuty@189.cn']
    message = MIMEText(mail_msg, 'plain', 'utf8')
    image_path = mail_image
    image_part = MIMEImage(open(image_path, mode='rb').read())
    image_part.add_header('Content-Disposition', 'attachment', filename=mail_image.split('\\')[-1])
    m = MIMEMultipart()
    m.attach(message)
    m.attach(image_part)
    m['From'] = f'{sender}'
    m['To'] = ','.join(receivers)
    m['Subject'] = mail_title
    server.sendmail(sender, receivers, m.as_string())


def send_email_with_attachments(mail_msg, mail_attachment, mail_title):
    server = get_server()
    sender = '80708055@qq.com'
    receivers = ['foxhuty@189.cn']
    message = MIMEText(mail_msg, 'plain', 'utf8')
    attachment_path = mail_attachment
    attachment_part = MIMEApplication(open(attachment_path, mode='rb').read())
    attachment_part.add_header('Content-Disposition', 'attachment', filename=mail_attachment.split('\\')[-1])
    m = MIMEMultipart()
    m.attach(message)
    m.attach(attachment_part)
    m['From'] = f'{sender}'
    m['To'] = ','.join(receivers)
    m['Subject'] = mail_title
    server.sendmail(sender, receivers, m.as_string())


if __name__ == '__main__':
    msg = 'this is a test测试this is a test测试this is a test测试this is a test测试this is a test测试'
    # title = '.....test测试.test测试......'
    # send_email(msg, title)
    image = r'D:\爬虫数据\mygirl.jpg'
    attachment = r'D:\爬虫数据\weather_data11.xlsx'
    title = '美女来了'
    # name = image.split('\\')
    # print(name[-1])
    # print(','.join(['a','b','c']))
    # print('='.join(['a','b','c']))
    send_email_with_image(msg, image, title)
    send_email_with_attachments(msg, attachment, title)
